<template>
  <div class="prescription-tab">
    <el-card>
      <div class="header-bar">
        <el-input 
          v-model="searchForm.registerId" 
          placeholder="挂号ID" 
          style="width: 200px; margin-right: 12px;" 
        />
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="amount-info">
        <el-alert type="info" :closable="false" show-icon>
          本项目金额合计：<span style="color: #ff5500; font-weight: bold;">{{ totalAmount }}元</span>
        </el-alert>
      </div>
      <el-table 
        :data="prescriptionList" 
        border 
        style="width: 100%; margin-top: 18px;"
        row-key="drugId"
        @selection-change="handleSelectionChange"
      >
        <el-table-column 
          type="selection" 
          width="50" 
          :reserve-selection="true" 
        />
        <el-table-column prop="drugName" label="药品名称" />
        <el-table-column prop="drugUnit" label="单位" />
        <el-table-column prop="drugFormat" label="用法格式" />
        <el-table-column prop="drugPrice" label="单价" width="100" />
        <el-table-column label="数量" width="120">
          <template #default="{ row }">
            <el-button size="small" @click="decrease(row)">-</el-button>
            <span style="margin: 0 8px;">{{ row.drugNumber }}</span>
            <el-button size="small" @click="increase(row)">+</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="drugState" label="状态" width="100" />
        <!-- <el-table-column label="删除" width="80">
          <template #default="{ $index }">
            <el-button type="danger" size="small" @click="removeRow($index)">删除</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <div style="text-align: right; margin-top: 16px;">
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="handleHome">首页</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import request from '@/utils/request';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const searchForm = ref({ registerId: '' });
const prescriptionList = ref([]);
const selectedRows = ref([]);

// 金额合计：基于选中行计算
const totalAmount = computed(() => {
  return selectedRows.value.reduce(
    (sum, row) => sum + row.drugPrice * row.drugNumber,
    0
  ).toFixed(2);
});

// 查询药品列表并加载已有处方数据
const fetchDrugList = async () => {
  try {
    const drugRes = await request.get('/drug-infos/all');
    const allDrugs = drugRes.data || [];

    const registerId = searchForm.value.registerId || route.query.patientId || '';
    let patientPrescriptions = [];
    if (registerId) {
      const prescriptionRes = await request.get('/prescriptions/by-register-id', {
        params: { registerId: parseInt(registerId) },
      });
      patientPrescriptions = prescriptionRes.data || [];
    }

    const prescriptionMap = new Map();
    patientPrescriptions.forEach((pres) => prescriptionMap.set(pres.drugId, pres));

    const mergedList = allDrugs.map((drug) => {
      const pres = prescriptionMap.get(drug.id);
      return pres
        ? {
            id: pres.id,
            registerId: pres.registerId,
            drugId: drug.id,
            drugName: drug.drugName,
            drugUnit: drug.drugUnit,
            drugFormat: drug.drugFormat,
            drugPrice: drug.drugPrice,
            drugNumber: pres.drugNumber,
            drugState: pres.drugState,
          }
        : {
            id: null,
            registerId: registerId,
            drugId: drug.id,
            drugName: drug.drugName,
            drugUnit: drug.drugUnit,
            drugFormat: drug.drugFormat,
            drugPrice: drug.drugPrice,
            drugNumber: 1,
            drugState: '已开立',
          };
    });

    prescriptionList.value = mergedList;
  } catch (error) {
    console.error('加载失败:', error);
    ElMessage.error('数据加载失败');
    prescriptionList.value = [];
  }
};

const handleSearch = async () => {
  await fetchDrugList();
};

const resetSearch = async () => {
  searchForm.value.registerId = '';
  await fetchDrugList();
};

const increase = (row) => {
  row.drugNumber++;
};

const decrease = (row) => {
  if (row.drugNumber > 1) row.drugNumber--;
};

const removeRow = (index) => {
  prescriptionList.value.splice(index, 1);
};

const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

const handleSubmit = async () => {
  const selected = selectedRows.value.filter((item) => item.drugNumber > 0);
  if (!selected.length) {
    ElMessage.warning('请选择要开立的药品');
    return;
  }

  const registerId = searchForm.value.registerId || route.query.patientId || '';
  if (!registerId) {
    ElMessage.warning('请输入挂号ID');
    return;
  }

  const batchData = selected.map((item) => ({
    registerId: registerId,
    drugId: item.drugId,
    drugUsage: item.drugUsage,
    drugNumber: item.drugNumber,
    drugState: '已开立',
  }));

  try {
    await request.post('/prescriptions/batch', batchData);
    ElMessage.success('处方已成功保存');
    await fetchDrugList();
  } catch (e) {
    ElMessage.error('保存失败: ' + (e.message || '未知错误'));
  }
};

const handleHome = () => {
  router.push('/');
};

onMounted(() => {
  fetchDrugList();
});
</script>

<style scoped>
.prescription-tab {
  padding: 12px 0;
}
.header-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}
.amount-info {
  margin-bottom: 16px;
}
</style>
